package com.clas.liu.myapplication.view.activity.impl;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.clas.liu.myapplication.R;
import com.clas.liu.myapplication.model.entity.info.Info;
import com.clas.liu.myapplication.model.entity.info.InfoData;
import com.clas.liu.myapplication.model.entity.info.InfoRoot;
import com.clas.liu.myapplication.model.entity.user.UserData;
import com.clas.liu.myapplication.model.entity.user.UserRoot;
import com.clas.liu.myapplication.presenter.impl.UserInfoPresenter;
import com.clas.liu.myapplication.view.activity.i.IUserInfoActivity;
import com.clas.liu.myapplication.view.adapter.UserInfoAdapter;
import com.clas.liu.myapplication.view.util.NetworkHelper;
import com.clas.liu.myapplication.view.util.SaveUtil;
import com.clas.liu.myapplication.view.widget.CircleImageView;
import com.hyphenate.easeui.EaseConstant;
import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by liu on 2019/5/6.
 */

public class UserInfoActivity extends BaseActivity<UserInfoPresenter> implements IUserInfoActivity,View.OnClickListener {

    private ImageView back;
    private CircleImageView head;
    private TextView title;
    private TextView age;
    private TextView school;
    private TextView zhuanye;
    private TextView introduction;
    private TextView name;
    private ImageView sex;
    private LinearLayout floatingView;
    private LinearLayout jubaoView;
    private LinearLayout chatView;
    private AppBarLayout appBarLayout;
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerView;

    private UserInfoAdapter adapter;
    private LinearLayoutManager layoutManager;

    private int id;
    private int page_no = 1;
    private final int page_size = 10;
    private boolean isRefresh = true;
    private boolean isAll = false;
    private int lastVisibleItem;

    private UserData user;
    private List<Info> infos;
    private boolean isSelf = false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info_layout );
        setStatusBarTransparent();
        findView();
        init();
        setListener();
    }

    private void init() {
        id = getIntent().getIntExtra("user_id",0);
        if (id != 0)
            mPresenter.getUser(id);
        UserData localUser;
        try {
             localUser = SaveUtil.<UserData>getFromLocal(this.getApplicationContext(), "user");
        } catch (Exception e) {
            e.printStackTrace();
            localUser = null;
           gotoLogin();
        }

        if (localUser == null || localUser.getId() == 0) {
           gotoLogin();
        }
        if (localUser!=null && id == localUser.getId()) {
            isSelf = true;
        }
        if (isSelf) {
            floatingView.setVisibility(View.GONE);
        }
    }

    public void gotoLogin() {
        showToast("当前登录异常，重新登录！",Toast.LENGTH_SHORT);
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
        finish();
    }
    private void setListener() {
        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if(verticalOffset!=0){
                    refreshLayout.setEnabled(false);
                    if (appBarLayout.getTotalScrollRange()-Math.abs(verticalOffset)<=20){
                        if (user!=null)
                            title.setText(user.getName());
                        back.setImageResource(R.mipmap.back);
                    }else{
                        title.setText(" ");
                        back.setImageResource(R.mipmap.back_white);
                    }
                }else {
                    refreshLayout.setEnabled(true);
                }
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                infoRefresh();
            }
        });
        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (adapter != null && newState == RecyclerView.SCROLL_STATE_IDLE
                        && lastVisibleItem + 1 == adapter.getItemCount()) {
                    if (!isAll)
                        mPresenter.getInfo(id,0,page_no,page_size);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        back.setOnClickListener(this);
        chatView.setOnClickListener(this);
        jubaoView.setOnClickListener(this);
    }

    private void infoRefresh() {
        if (NetworkHelper.isNetworkAvailable(this)){
            page_no = 1;
            isRefresh = true;
            mPresenter.getInfo(id,0,page_no, page_size);
        }else {
            refreshLayout.setRefreshing(false);
            showToast("亲亲，网好像断了呢!~",Toast.LENGTH_SHORT);
        }
    }

    private void findView() {
        back = findViewById(R.id.user_info_back);
        head = findViewById(R.id.user_info_head);
        title = findViewById(R.id.user_title);
        sex = findViewById(R.id.user_info_sex);
        age = findViewById(R.id.user_info_age);
        school = findViewById(R.id.user_info_school);
        zhuanye = findViewById(R.id.user_info_zhuanye);
        introduction = findViewById(R.id.user_info_introduction);
        floatingView = findViewById(R.id.user_info_floating_view);
        jubaoView = findViewById(R.id.user_info_jubao);
        chatView = findViewById(R.id.user_info_chat);
        appBarLayout = findViewById(R.id.user_info_appbar_layout);
        name = findViewById(R.id.user_info_name);
        refreshLayout = findViewById(R.id.user_info_refresh_layout);
        recyclerView = findViewById(R.id.user_info_rv);
    }

    @Override
    public void failBecauseNetReturn(int code) {
        showToast(code+"请求失败！", Toast.LENGTH_SHORT);
    }

    @Override
    public void userReturn(UserRoot root) {
        if (root.getCode() == 0 ) {
            UserData user = root.getData();
            this.user = user;
            Picasso.with(this).load(user.getHead()).error(R.mipmap.default_head).into(head);
            name.setText(user.getName());
            age.setText(String.valueOf(user.getAge()));
            if (user.getSchool()!=null && !user.getSchool().equals("") && !user.getSchool().equals("null"))
                school.setText("学院："+user.getSchool());
            else school.setText("学院：未填写");
            if (user.getInstitute()!=null && !user.getInstitute().equals("") && !user.getInstitute().equals("null"))
                zhuanye.setText("专业："+user.getInstitute());
            else zhuanye.setText("专业：未填写");
            if (user.getSex().equals("女"))
                sex.setImageResource(R.mipmap.woman);
            else sex.setImageResource(R.mipmap.man);
            if (user.getIntroduction()!=null && !user.getIntroduction().equals("") &&
                    !user.getIntroduction().equals("null") )
                introduction.setText(user.getIntroduction());
            else introduction.setText("万花丛中过，片叶不沾身~");
            mPresenter.getInfo(id,0,page_no,page_size);
        }else {
            showToast(root.getMessage(),Toast.LENGTH_SHORT);
        }

    }

    @Override
    public void infoReturn(InfoRoot root) {
        InfoData data = root.getData();
        infos = data.getData();
        refreshLayout.setRefreshing(false);
        if (isRefresh) {
            if (adapter!=null)
                adapter.deleteLoadingMore(false);
        }
        refreshLayout.setRefreshing(false);
        if (layoutManager == null){
            layoutManager = new LinearLayoutManager(this);
            recyclerView.setLayoutManager(layoutManager);
        }
        if (adapter == null ){
            adapter = new UserInfoAdapter(this,infos);
            recyclerView.setAdapter(adapter);
        }else
            adapter.update(infos);
        if(data.getPageNum() == data.getPages()) {
            adapter.deleteLoadingMore(true);
            isAll = true;
        }else if (data.getPageNum() < data.getPages()){
            page_no++;
            isAll = false;
        }
    }

    @Override
    public void jubaoReturn() {

    }

    @Override
    protected UserInfoPresenter getPresenter() {
        return new UserInfoPresenter(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.user_info_back:
                finish();
                break;
            case R.id.user_info_chat:
                intent = new Intent(this,ChatActivity.class);
                intent.putExtra(EaseConstant.EXTRA_USER_ID,String.valueOf(user.getId()));
                intent.putExtra("name",user.getName());
                intent.putExtra("head",user.getHead());
                startActivity(intent);
                break;
            case R.id.user_info_jubao:
                intent = new Intent(this,ReportActivity.class);
                intent.putExtra("user_id",user.getId());
                startActivity(intent);
                break;
        }
    }
}
